﻿using System;
using System.Web.UI;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.Navigation;
using System.Web;

namespace NewsGroupListWebPart
{
    [Guid("9ea6a7f9-57d6-4e76-ba16-137c0b2fe575")]
    public class NewsGroupListWebPart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private DataTable articleDataTable = new DataTable("Newsgroup");
        private SPGridView gridView;
        private bool _showFrom = true;
        private bool _showDate = true;
        private bool _showHeader = true;
        private string _newsgroup = "mw.rec.bboard";
        private int _maxNumberOfArticles = 10;

        //setup tool parts vars
        public string newsgroup
        {
            get { return _newsgroup; }
            set { _newsgroup = value; }
        }

        [
            WebBrowsable(true),
            Personalizable(PersonalizationScope.Shared),
            DefaultValue(10),
            WebDescription("Maximum # of articles to display (max 100)"),
            WebDisplayName("Maximum # of articles to display (max 100)"),
            Category("Article Display Settings")]
        public int MaxNumberOfArticles
        {
            get { return _maxNumberOfArticles; }
            set
            {
                if (value > 100)
                {
                    _maxNumberOfArticles = 100;
                }
                else
                {
                    _maxNumberOfArticles = value;
                }
            }
        }

        [
            WebBrowsable(true),
            Personalizable(PersonalizationScope.Shared),
            DefaultValue(true),
            WebDescription("Show \"From\" Column"),
            WebDisplayName("Show \"From\" Column"),
            Category("Article Display Settings")]
        public bool showFrom
        {
            get { return _showFrom; }
            set { _showFrom = value; }
        }

        [
            WebBrowsable(true),
            Personalizable(PersonalizationScope.Shared),
            DefaultValue(true),
            WebDescription("Show Table Header"),
            WebDisplayName("Show Table Header"),
            Category("Article Display Settings")]
        public bool showHeader
        {
            get { return _showHeader; }
            set { _showHeader = value; }
        }

        [
            WebBrowsable(true),
            Personalizable(PersonalizationScope.Shared),
            DefaultValue(true),
            WebDescription("Show \"Date\" Column"),
            WebDisplayName("Show \"Date\" Column"),
            Category("Article Display Settings")]
        public bool showDate
        {
            get { return _showDate; }
            set { _showDate = value; }
        }

        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolparts = new ToolPart[3];
            WebPartToolPart wptp = new WebPartToolPart();
            CustomPropertyToolPart custom = new CustomPropertyToolPart();
            toolparts[0] = new CustomToolPart();
            toolparts[1] = custom;
            toolparts[2] = wptp;

            return toolparts;
        }

        private void setupDataColumns()
        {
            if (articleDataTable != null)
            {
                if (!articleDataTable.Columns.Contains("PostID"))
                {
                    articleDataTable.Columns.Add("PostID", typeof(string));
                }
                if (!articleDataTable.Columns.Contains("Post Subject"))
                {
                    articleDataTable.Columns.Add("Post Subject", typeof(string));
                }
                if (showFrom == true)
                {
                    if (!articleDataTable.Columns.Contains("Post From"))
                    {
                        articleDataTable.Columns.Add("Post From", typeof(string));
                    }
                }
                if (showDate == true)
                {
                    if (!articleDataTable.Columns.Contains("Post Date"))
                    {
                        articleDataTable.Columns.Add("Post Date", typeof(DateTime));
                    }
                }
            }
        }

        private void setupGridView()
        {
            gridView = new SPGridView();
            gridView.AutoGenerateColumns = false;
            gridView.DataSource = articleDataTable;

            SPBoundField ItemID = new SPBoundField();
            ItemID.DataField = "PostID";
            ItemID.HeaderText = "PostID";
            ItemID.Visible = false;
            gridView.Columns.Add(ItemID);

            HyperLinkField hlf = new HyperLinkField();
            hlf.HeaderText = "Post Subject";
            hlf.DataNavigateUrlFields = new[] { "PostID" };
            string newsgroupSimple = Regex.Replace(newsgroup, "[^A-Za-z0-9]", "");
            hlf.DataNavigateUrlFormatString = "http://" + SPContext.Current.Site.HostName + "/news/Lists/" + newsgroupSimple + "/DispForm.aspx?ID={0}";
            hlf.DataTextField = "Post Subject";
            gridView.Columns.Add(hlf);

            if (showFrom == true)
            {
                SPBoundField from = new SPBoundField();
                from.DataField = "Post From";
                from.HeaderText = "Post From";
                gridView.Columns.Add(from);
            }
            if (showDate == true)
            {
                SPBoundField date = new SPBoundField();
                date.DataField = "Post Date";
                date.HeaderText = "Post Date";
                gridView.Columns.Add(date);
            }
            if (showHeader == false)
            {
                gridView.ShowHeader = false;
            }

            Controls.Add(gridView);
            gridView.DataBind(); //This line has to be after when the gridView has been added to the Controls collection
        }

        private void getNewsDataIntoGrid()
        {
            try
            {
                using (SPSite site = new SPSite("http://" + SPContext.Current.Site.HostName + "/news"))
                {
                    using (SPWeb web = site.RootWeb)
                    {

                        string newsgroupSimple = Regex.Replace(newsgroup, "[^A-Za-z0-9]", "");
                        SPList oList = web.GetList("http://" + SPContext.Current.Site.HostName + "/news/Lists/" + newsgroupSimple + "/AllItems.aspx");

                        SPQuery query = new SPQuery();
                        query.RowLimit = Convert.ToUInt16(MaxNumberOfArticles);
                        query.ViewFields = "<FieldRef Name='ID' />" +
                                          "<FieldRef Name='Title' />" +
                                          "<FieldRef Name='PostID' />" +
                                          "<FieldRef Name='PostDate' />" +
                                          "<FieldRef Name='PostFrom' />" +
                                          "<FieldRef Name='PostSubject' />" +
                                          "<FieldRef Name='Modified' />";
                        query.Query = "<OrderBy>" +
                                          "<FieldRef Name='ID' Ascending='False' />" +
                                       "</OrderBy>";

                        SPListItemCollection items = oList.GetItems(query);

                        foreach (SPItem item in items)
                        {
                            DataRow row = articleDataTable.NewRow();
                            row["PostID"] = item["ID"].ToString();
                            row["Post Subject"] = item["Post Subject"].ToString();
                            if (showFrom == true)
                            {
                                row["Post From"] = item["Post From"].ToString();
                            }
                            if (showDate == true)
                            {
                                row["Post Date"] = Convert.ToDateTime(item["Post Date"].ToString());
                            }
                            articleDataTable.Rows.Add(row);
                        }
                    }
                }
            }
            catch
            {
                DataRow row = articleDataTable.NewRow();
                row["PostID"] = "0";
                row["Post Subject"] = "No List Found";
                articleDataTable.Rows.Add(row);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            setupDataColumns();
            getNewsDataIntoGrid();
            setupGridView();
            this.Title = "Latest posts from " + newsgroup;
            string newsgroupSimple = Regex.Replace(newsgroup, "[^A-Za-z0-9]", "");
            this.TitleUrl = "http://" + SPContext.Current.Site.HostName + "/news/Lists/" + newsgroupSimple + "/";
        }

        public NewsGroupListWebPart()
        {

        }
    }
}
